package com.thghh.resource;

import com.thghh.resource.util.ResourceLoaderUtils;
import com.thghh.resource.util.StringUtil;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * A {@link ResourceLoader} that uses a {@link Map} with {@code byte[]} as its source of Resources. This is similar to
 * {@link StringResourceLoader}, but uses {@code byte[]} instead of {@link String}; see more details there.
 *
 * @since 2.3.24
 */
public class ByteArrayResourceLoader implements ResourceLoader {

    private final Map<String, ByteArrayResourceSource> Resources = new HashMap<>();

    /**
     * Adds a Resource to this Resource loader; see {@link StringResourceLoader#putResource(String, String)} for more.
     */
    public void putResource(String name, byte[] ResourceContent) {
        putResource(name, ResourceContent, System.currentTimeMillis());
    }

    /**
     * Adds a Resource to this Resource loader; see {@link StringResourceLoader#putResource(String, String, long)} for
     * more.
     */
    public void putResource(String name, byte[] ResourceContent, long lastModified) {
        Resources.put(name, new ByteArrayResourceSource(name, ResourceContent, lastModified));
    }

    /**
     * Removes the Resource with the specified name if it was added earlier.; see
     * {@link StringResourceLoader#removeResource(String)} for more details.
     *
     * @since 2.3.26
     */
    public boolean removeResource(String name) {
        return Resources.remove(name) != null;
    }

    @Override
    public void closeResource(Object ResourceSource) {
    }

    @Override
    public Object findResource(String name) {
        return Resources.get(name);
    }

    @Override
    public long getLastModified(Object ResourceSource) {
        return ((ByteArrayResourceSource) ResourceSource).lastModified;
    }

    @Override
    public Reader getReader(Object templateSource, String encoding) throws UnsupportedEncodingException {
        return new InputStreamReader(
                new ByteArrayInputStream(((ByteArrayResourceSource) templateSource).resourceContent),
                encoding);
    }

    private static class ByteArrayResourceSource {
        private final String name;
        private final byte[] resourceContent;
        private final long lastModified;

        ByteArrayResourceSource(String name, byte[] resourceContent, long lastModified) {
            if (name == null) {
                throw new IllegalArgumentException("name == null");
            }
            if (resourceContent == null) {
                throw new IllegalArgumentException("ResourceContent == null");
            }
            if (lastModified < -1L) {
                throw new IllegalArgumentException("lastModified < -1L");
            }
            this.name = name;
            this.resourceContent = resourceContent;
            this.lastModified = lastModified;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            ByteArrayResourceSource other = (ByteArrayResourceSource) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }

    }

    /**
     * Show class name and some details that are useful in Resource-not-found errors.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(ResourceLoaderUtils.getClassNameForToString(this));
        sb.append("(Map { ");
        int cnt = 0;
        for (String name : Resources.keySet()) {
            cnt++;
            if (cnt != 1) {
                sb.append(", ");
            }
            if (cnt > 10) {
                sb.append("...");
                break;
            }
            sb.append(StringUtil.jQuote(name));
            sb.append("=...");
        }
        if (cnt != 0) {
            sb.append(' ');
        }
        sb.append("})");
        return sb.toString();
    }

}
